package com.xxxx.core.controller;

import com.xxxx.common.login.model.LoginUser;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.InvalidSessionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 名称：BaseController
 * 描述：基本的控制器，集成与父类ControllerSupport，
 * 该类提供设置与获取session，request，response的方法，父类提供一系列的支持方法，
 * 自定义业务层controller需继承该类方可使用封装好的方法。
 * 作者：vvvv
 * 时间：2018/5/28 09:53
 */
public class BaseController extends ControllerSupport {
    /**
     * 服务器会话信息 session 对象
     */
    private HttpSession session;

    /**
     * 用户请求 request 对象
     */
    private HttpServletRequest request;

    /**
     * 服务器响应结果 response 对象
     */
    private HttpServletResponse response;

    /**
     * 获取 服务器会话信息 session 对象
     */
    public HttpSession getSession() {
        return this.session;
    }

    /**
     * 设置 服务器会话信息 session 对象
     */
    public void setSession(HttpSession session) {
        this.session = session;
    }

    /**
     * 获取 用户请求 request 对象
     */
    public HttpServletRequest getRequest() {
        return this.request;
    }

    /**
     * 设置 用户请求 request 对象
     */
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 获取 服务器响应结果 response 对象
     */
    public HttpServletResponse getResponse() {
        return this.response;
    }

    /**
     * 设置 服务器响应结果 response 对象
     */
    public void setResponse(HttpServletResponse response) {
        this.response = response;
    }

    protected LoginUser getSessionUser() {
        return (LoginUser) this.session.getAttribute("user");
    }

    /**
     * 统一异常处理类
     *
     * @param request   the request
     * @param response  the response
     * @param exception the exception
     * @return the string
     */
    protected String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
        // 统一异常处理类
        request.setAttribute("ex", exception);
        if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
            request.setAttribute("requestHeader", "ajax");
        }
        // shiro 没有权限异常
        if (exception instanceof UnauthorizedException) {
            return "/403/error";
        }
        if (exception instanceof InvalidSessionException) {
            return "/login";
        }
        return "500/error";
    }
}
